package cn.e4j.modular.crm.service.impl;

import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.StringUtils;
import cn.e4j.modular.crm.entity.GwamT;
import cn.e4j.modular.crm.entity.GwecT;
import cn.e4j.modular.crm.mapper.GwecTMapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 * <p>
 *  发货通知单 服务实现类
 * </p>
 *
 * @author miaoyl
 * @since 2019-03-07
 */
@Service
public class GwecTServiceImpl extends ServiceImpl<GwecTMapper, GwecT> {

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getListPage(Page<Object> page, Dto dto) {
        List<Map<String, Object>> gwdcDtos = new ArrayList<>();
        if(dto.getString("mlegal") == null || dto.getString("mlegal") == ""){
            return gwdcDtos;
        }
        gwdcDtos = this.baseMapper.getListPage(page, dto);
        return gwdcDtos;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getCOPTCList(Page<Object> page, Dto dto) {
        List<Map<String, Object>> tcDtos = this.baseMapper.getCOPTCList(page, dto);
        return tcDtos;
    }

    @Transactional
    public String transform(List<GwecT> xlist, List<GwecT> ylist, String mlegal){
        //获取当天最大销货单号
        ShiroUser shiroUser = ShiroKit.getUser();
        String result = "";
        String TG002 = this.getMaxTG002(mlegal, DateUtils.formatDate(new Date(),"yyyyMMdd"));
        for (GwecT xDto:xlist) {
            String mlegal_x = xDto.getGWECMLEGAL();
            String TC004 = xDto.getGWEC004();
            String TC020 = xDto.getGWEC102();
            Date date = new Date();
            String GWECDOCNO = "CHD"+ DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMddHHmmssSSS);
            int count = 1;
            Dto queryDto = Dtos.newDto();
            for(GwecT yDto:ylist){
                //根据客户+返利类型+法人进行分单，写入出货通知单表及ERP销货单表
                if(mlegal_x.equals(yDto.getGWECMLEGAL())  && TC004.equals(yDto.getGWEC004())  && TC020.equals(yDto.getGWEC102()) ){
                    //根据所选ERP单号+项次获取数据
                    Dto COPTC_D = this.getCOPTCList(yDto.getGWECMLEGAL(), yDto.getGWEC003(), yDto.getGWEC103());
                    queryDto = COPTC_D;
                    //根据品号查询产品资料
                    Dto gwam = this.baseMapper.getGwam(shiroUser.getDBC(),COPTC_D.getString("TD004"));
                    //写入出货通知单
                    GwecT gwecT = new GwecT();
                    gwecT.setGWECENT(shiroUser.getDBC());
                    gwecT.setGWECDOCNO(GWECDOCNO);//单号
                    gwecT.setGWECSEQ(new BigDecimal(count));//单号
                    gwecT.setGWECDOCDATE(LocalDate.now());//单据日期
                    gwecT.setGWEC003(yDto.getGWEC003());//ERP订单号
                    gwecT.setGWEC004(COPTC_D.getString("TD004"));//品号
                    gwecT.setGWEC005(COPTC_D.getString("TC004"));//客户
                    gwecT.setGWEC008(COPTC_D.getString("TC007"));//仓库
                    gwecT.setGWEC009(COPTC_D.getString("TC008"));//数量
                    gwecT.setGWEC016("Y");//有效码

                    //写入erp销货单身表
                    this.insertGOPTH(COPTC_D, GWECDOCNO, count , TG002, gwam, mlegal);
                    gwecT.insert();
                    count ++;

                }
            }
            //根据单号查询单身数据汇总
            Dto COPTHSum = this.baseMapper.getCOPTHSum(mlegal, String.valueOf(TG002));
            //写入erp销货单头表
            this.insertGOPTG(queryDto, GWECDOCNO, count , TG002, COPTHSum, mlegal);
            result = result + TG002 + ",\n";
            BigDecimal num = new BigDecimal(TG002).add(new BigDecimal(1));
            TG002 = num.toString();
        }
        result = StringUtils.substringBeforeLast(result, ",");
        return result;
    }

    @Transactional(readOnly = true)
    public String getMaxTG002(String mlegal, String sys_time) {
        Dto maxTG002 = this.baseMapper.getMaxTG002(mlegal, sys_time);
        String TG002_MAX = "";
        if(maxTG002 != null){
            BigDecimal num = maxTG002.getBigDecimal("TG002").add(new BigDecimal(1));
            TG002_MAX = num.toString();
        }else {
            TG002_MAX = DateUtils.formatDate(new Date(),"yyyyMMdd")+"001";
        }
        return TG002_MAX;
    }

    @Transactional(readOnly = true)
    public Dto getCOPTCList(String mlegal,String TC002, String TD003) {
        Dto COPTC = this.baseMapper.getCOPTC(mlegal, TC002, TD003);
        return COPTC;
    }

    @Transactional(readOnly = true)
    public Dto getCOPTHSum(String mlegal,String TG002) {
        Dto COPTHSum = this.baseMapper.getCOPTHSum(mlegal, TG002);
        return COPTHSum;
    }

    @Transactional(readOnly = true)
    public Dto getGwam(String mlegal,String TD004) {
        Dto gwam = this.baseMapper.getGwam(mlegal, TD004);
        return gwam;
    }

    @Transactional
    public void insertGOPTH(Dto COPTC_D, String GWECDOCNO, int count, String TG002, Dto gwam, String mlegal) {
        Dto MD003 = this.baseMapper.getMD003(mlegal,COPTC_D.getString("TD004"), COPTC_D.getString("TD036"));
        Dto COPTH = Dtos.newDto();
        COPTH.put("TH001","FXFH");//单别
        COPTH.put("TH002", TG002);//单号
        COPTH.put("TH003", count);//序号
        COPTH.put("TH004", COPTC_D.getString("TD004"));//品号
        COPTH.put("TH005", COPTC_D.getString("TD005"));//品名
        COPTH.put("TH006", COPTC_D.getString("TD006"));//规格
        COPTH.put("TH007", COPTC_D.getString("TD007"));//仓库
        COPTH.put("TH008", COPTC_D.getBigDecimal("TD008"));//数量
        COPTH.put("TH009", COPTC_D.getString("TD010"));//单位
        COPTH.put("TH012", COPTC_D.getBigDecimal("TD011"));//单价
        COPTH.put("TH013", COPTC_D.getBigDecimal("TD012"));//金额
        COPTH.put("TH014", COPTC_D.getString("TC001"));//订单单别
        COPTH.put("TH015", COPTC_D.getString("TC002"));//订单单号
        COPTH.put("TH016", COPTC_D.getString("TD003"));//订单序号
        COPTH.put("TH017", "********************");//订单序号
        COPTH.put("TH018", COPTC_D.getString("TD020")); //备注活动说明
        COPTH.put("TH020", "N");//审核否
        COPTH.put("TH021", "N");//Y/N
        COPTH.put("TH025", COPTC_D.getBigDecimal("TD026"));//折扣率(默认订单折扣率)
        COPTH.put("TH026", "N");//Y/N
        COPTH.put("TH031", "1");
        COPTH.put("TH035", COPTC_D.getBigDecimal("TD038"));//原币税前金额
        COPTH.put("TH036", COPTC_D.getBigDecimal("TD039"));//原币税额
        COPTH.put("TH037", COPTC_D.getBigDecimal("TD038").multiply(COPTC_D.getBigDecimal("TC009")));//本币税前金额
        COPTH.put("TH038", COPTC_D.getBigDecimal("TD039").multiply(COPTC_D.getBigDecimal("TC009")));//本币税额
        if(MD003 != null){
            COPTH.put("TH039", COPTC_D.getBigDecimal("TD008").multiply(MD003.getBigDecimal("MD003")));//包装数量
        }else {
            COPTH.put("TH039", COPTC_D.getBigDecimal("TD008").multiply(new BigDecimal(0)));//包装数量
        }
        COPTH.put("TH041", COPTC_D.getString("TD036"));//包装单位（同单位改为默认TD036）
        COPTH.put("TH048", COPTC_D.getBigDecimal("TD037"));//税率
        COPTH.put("TH042", 0);//已开票数量
        COPTH.put("TH056", "##########");//库位
        COPTH.put("TH059", GWECDOCNO);//出货通知单单号
        COPTH.put("TH058", count);//出货通知单项次
        COPTH.put("UDF02", "");//客户自定字段
        COPTH.put("UDF11", "");//类型1（待定）
        COPTH.put("UDF12", COPTC_D.getString("TC200"));//订单返利类型
        if(COPTH.getString("TH039")!= "" && COPTH.getBigDecimal("TH039").compareTo(new BigDecimal(0)) == 1){
            BigDecimal UDF56 = COPTH.getBigDecimal("TH012").multiply(COPTH.getBigDecimal("TH008")).divide
                    (COPTH.getBigDecimal("TH039"),2,ROUND_HALF_DOWN);
            COPTH.put("UDF56", UDF56);
        }else {
            COPTH.put("UDF56", COPTC_D.getBigDecimal("TC200"));//出厂价结算价
        }
        if(gwam != null && gwam.getString("GWAM021") != "0"){
            COPTH.put("UDF57", gwam.getBigDecimal("GWAM021").multiply(COPTC_D.getBigDecimal("TD008")));//发货体积
        }
        if(gwam != null && gwam.getString("GWAM024") != "0") {
            COPTH.put("UDF58", gwam.getBigDecimal("GWAM024").multiply(COPTC_D.getBigDecimal("TD008")));//发货重量
        }

        COPTH.put("COMPANY", mlegal);
        COPTH.put("CREATE_DATE", DateUtils.formatDate(new Date(),"yyyyMMddHHmmssSSS"));
        COPTH.put("FLAG", 1);

        COPTH.put("mlegal",mlegal);
        this.baseMapper.insertCOPTH(COPTH);
    }

    @Transactional
    public void insertGOPTG(Dto COPTC_D, String GWECDOCNO, int count, String TG002, Dto COPTHSum, String mlegal) {
        Date date = new Date();
        Dto COPTG = Dtos.newDto();
        COPTG.put("TG001","FXFH");//单别
        COPTG.put("TG002",TG002);//单号
        COPTG.put("TG003", DateUtils.formatDate(date,"yyyyMMdd"));//销货日期
        COPTG.put("TG004", COPTC_D.getString("TC004"));//客户编号
        COPTG.put("TG005", COPTC_D.getString("TC005"));//部门
        COPTG.put("TG006", COPTC_D.getString("TC006"));//业务员
        COPTG.put("TG008", COPTC_D.getString("TC010"));//送货地址
        COPTG.put("TG010", "01");//出货工厂
        COPTG.put("TG011", COPTC_D.getString("TC008"));//币种
        COPTG.put("TG012", COPTC_D.getBigDecimal("TC009"));//汇率
        COPTG.put("TG013", COPTHSum.getBigDecimal("TH035_SUM"));//原币销货金额
        COPTG.put("TG016", "A");//发票类型
        COPTG.put("TG017", "1");//1.应税内含、2.应税外加、9.不计税
        COPTG.put("TG022", 0);//打印次数
        COPTG.put("TG023", "N");//状态
        COPTG.put("TG024", "N");//更新码Y/N
        COPTG.put("TG025", COPTHSum.getBigDecimal("TH036_SUM"));//原币销货税额
        COPTG.put("TG026", COPTC_D.getString("TC006"));//收款业务员
        COPTG.put("TG031", "N");//烟酒注记
        COPTG.put("TG032", 0);//件数
        COPTG.put("TG033", COPTHSum.getBigDecimal("TH008_SUM"));//总数量
        COPTG.put("TG036", "N");
        COPTG.put("TG037", "N");
        COPTG.put("TG042", DateUtils.formatDate(date,"yyyyMMdd"));//单据日期
        COPTG.put("TG044", COPTC_D.getBigDecimal("TD037"));//税率
        COPTG.put("TG045", COPTHSum.getBigDecimal("TH035_SUM").multiply(COPTC_D.getBigDecimal("TC009")));//本币销货金额
        COPTG.put("TG046", COPTHSum.getBigDecimal("TH036_SUM").multiply(COPTC_D.getBigDecimal("TC009")));//本币销货税额
        String UDF12 = COPTC_D.getString("UDF12");
        if(UDF12.startsWith("帐期")){//帐期% 3,4
            if(COPTC_D.getString("TC042").equals("208") || COPTC_D.getString("TC042").equals("209")){
                COPTG.put("TG047", "201");//付款条件编号
            }else if(COPTC_D.getString("TC042").equals("201")){
                COPTG.put("TG047", "201");//付款条件编号
            }else if(COPTC_D.getString("TC042").equals("207")){
                COPTG.put("TG047", "207");//付款条件编号
            }
        }else if(UDF12.startsWith("现款")){//现款 1,2
            COPTG.put("TG047", "208");//付款条件编号
        }else if(UDF12.startsWith("铺货")){//铺货
            COPTG.put("TG047", "209");//付款条件编号
        }
        COPTG.put("TG055", "N");
        COPTG.put("TG056", "N");
        COPTG.put("TG059", "N");
        COPTG.put("UDF07", COPTC_D.getString("TD007"));//仓库
        COPTG.put("UDF11", GWECDOCNO);//出货通知单
        COPTG.put("UDF12", UDF12);//返利类型
        COPTG.put("UDF51", COPTHSum.getBigDecimal("UDF57_SUM"));//发货总体积
        COPTG.put("UDF52", COPTHSum.getBigDecimal("UDF58_SUM"));//发货总重量
        Dto CMSNA = this.baseMapper.getCMSNA(mlegal, COPTG.getString("TG003"), COPTG.getString("TG047"));
        if(CMSNA != null){
            COPTG.put("TG200", CMSNA.getString("TG200"));
        }else {
            COPTG.put("TG200", COPTG.getString("TG003"));
        }
        COPTG.put("TG201","");

        COPTG.put("COMPANY", mlegal);
        COPTG.put("CREATE_DATE", DateUtils.formatDate(new Date(),"yyyyMMddHHmmssSSS"));
        COPTG.put("FLAG", 1);

        COPTG.put("mlegal",mlegal);
        this.baseMapper.insertCOPTG(COPTG);
    }

    public void delGwec(String ent, String GWDCDOCNO){
        GwecT gwecT = new GwecT();
        UpdateWrapper<GwecT> gwecTUpdateWrapper = new UpdateWrapper<>();
        gwecTUpdateWrapper.eq("GWECENT", ent);
        gwecTUpdateWrapper.eq("GWECDOCNO", GWDCDOCNO);
        gwecT.delete(gwecTUpdateWrapper);
    }

    public void delGOPTH(String mlegal, String TG002){
        this.baseMapper.delCOPTH(mlegal,TG002);
    }

    @Transactional(readOnly = true)
    public List<Dto> getErr(Dto dto) {
        List<Dto> errData = this.baseMapper.getFreeData(dto);
        return errData;
    }
}
